from textual.widgets import DataTable
from rich.text import Text


class FileEditTable(DataTable):

    def __init__(self, id, file_name):  # file_name = file_path
        super().__init__()
        self.id = id
        self.file_name = file_name
    
    def on_mount(self):
        self.cursor_type = "row"
        with open(self.file_name, 'r') as f:
            self.content = f.readlines()
        self.add_columns(self.file_name)
        if len(self.content)==0:
            self.content.append("----空文件----")

        for number, row in enumerate(self.content, start=1):
            label = Text(str(number), style="#B0FC38 italic")
            self.add_row(row, label=label)
        self.can_focus=False

    def on_data_table_row_highlighted(self):
        highlight_line_content = self.get_row_at(self.cursor_row)[0]
        input_widget = self.app.query_one("#file_edit_input")
        input_widget.value = highlight_line_content
        input_widget.cursor_position = 0

    def key_ctrl_c(self):
        self.app.pop_screen()
